const Router = require('koa-router')
const db = require('../db')
const axios = require('axios')
const crypto = require('crypto')
const { WX_APP_ID, WX_APP_SECRET } = require('../config')

const router = new Router({ prefix: '/api/login' })

// 微信登录接口
router.post('/wechat', async (ctx) => {
  const { code } = ctx.request.body
  
  if (!code) {
    ctx.status = 400
    ctx.body = { code: 400, message: '缺少code参数' }
    return
  }
  
  try {
    // 请求微信接口获取openid和session_key
    const wxResult = await axios.get('https://api.weixin.qq.com/sns/jscode2session', {
      params: {
        appid: WX_APP_ID,
        secret: WX_APP_SECRET,
        js_code: code,
        grant_type: 'authorization_code'
      }
    })
    
    const { openid, session_key } = wxResult.data
    
    if (!openid) {
      ctx.status = 400
      ctx.body = { code: 400, message: '获取微信openid失败' }
      return
    }
    
    // 检查用户是否已存在
    let userResults = await db.query('SELECT * FROM users WHERE openid = ?', [openid])
    let userId
    
    if (userResults.length === 0) {
      // 用户不存在，创建新用户
      const insertResult = await db.query(
        'INSERT INTO users (nickname, openid, session_key, created_at, last_login, points) VALUES (?, ?, ?, NOW(), NOW(), 100)',
        ['微信用户', openid, session_key]
      )
      userId = insertResult.insertId
    } else {
      // 用户已存在
      userId = userResults[0].id
      
      // 更新session_key和最后登录时间
      await db.query(
        'UPDATE users SET session_key = ?, last_login = NOW() WHERE id = ?',
        [session_key, userId]
      )
    }
    
    // 获取用户信息
    const [user] = await db.query(`
      SELECT 
        id, 
        nickname, 
        avatar, 
        student_id,
        courses_count,
        points
      FROM users 
      WHERE id = ?
    `, [userId])
    
    // 获取积分信息
    const [earnResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "earn"',
      [userId]
    )
    
    const [spendResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "spend"',
      [userId]
    )

    const totalPoints = Number(earnResults.total || 0)
    const usedPoints = Number(spendResults.total || 0)
    const availablePoints = totalPoints - usedPoints
    
    // 生成一个随机的token作为登录凭证
    const token = crypto.randomBytes(32).toString('hex')
    
    // 将token保存到Redis中，关联到用户ID
    const tokenKey = `auth:token:${token}`
    await new Promise((resolve, reject) => {
      const redisClient = require('../db/redis').client
      redisClient.setex(tokenKey, 30 * 24 * 60 * 60, userId.toString(), (err) => {
        if (err) reject(err)
        else resolve()
      })
    })
    
    // 设置会话
    ctx.session.userId = userId
    ctx.session.openid = openid
    
    ctx.body = {
      code: 200,
      data: {
        token,
        user: {
          id: user.id,
          nickname: user.nickname,
          avatar: user.avatar,
          studentId: user.student_id,
          coursesCount: user.courses_count,
          points: user.points,
          availablePoints: availablePoints
        }
      },
      message: '登录成功'
    }
  } catch (error) {
    console.error('微信登录失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 检查登录状态
router.get('/check', async (ctx) => {
  const { token } = ctx.request.query
  
  if (!token) {
    ctx.status = 401
    ctx.body = { code: 401, message: '未登录' }
    return
  }
  
  try {
    // 从Redis中获取用户ID
    const tokenKey = `auth:token:${token}`
    const userId = await new Promise((resolve, reject) => {
      const redisClient = require('../db/redis').client
      redisClient.get(tokenKey, (err, reply) => {
        if (err) reject(err)
        else resolve(reply)
      })
    })
    
    if (!userId) {
      ctx.status = 401
      ctx.body = { code: 401, message: 'token已过期或无效' }
      return
    }
    
    // 获取用户信息
    const users = await db.query(
      'SELECT id, nickname, avatar, student_id, points, courses_count FROM users WHERE id = ?',
      [userId]
    )
    
    if (users.length === 0) {
      ctx.status = 401
      ctx.body = { code: 401, message: '用户不存在' }
      return
    }
    
    const user = users[0]
    
    // 获取积分信息
    const [earnResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "earn"',
      [userId]
    )
    
    const [spendResults] = await db.query(
      'SELECT SUM(amount) as total FROM points_history WHERE user_id = ? AND type = "spend"',
      [userId]
    )

    const totalPoints = Number(earnResults.total || 0)
    const usedPoints = Number(spendResults.total || 0)
    const availablePoints = totalPoints - usedPoints
    
    ctx.body = {
      code: 200,
      data: {
        isLoggedIn: true,
        user: {
          id: user.id,
          nickname: user.nickname,
          avatar: user.avatar,
          studentId: user.student_id,
          coursesCount: user.courses_count,
          points: user.points,
          availablePoints: availablePoints
        }
      }
    }
  } catch (error) {
    console.error('检查登录状态失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

// 登出接口
router.post('/logout', async (ctx) => {
  const { token } = ctx.request.body
  
  if (!token) {
    ctx.status = 400
    ctx.body = { code: 400, message: '缺少token参数' }
    return
  }
  
  try {
    // 从Redis中删除token
    const tokenKey = `auth:token:${token}`
    await new Promise((resolve, reject) => {
      const redisClient = require('../db/redis').client
      redisClient.del(tokenKey, (err, reply) => {
        if (err) reject(err)
        else resolve(reply)
      })
    })
    
    // 清除会话
    ctx.session = null
    
    ctx.body = {
      code: 200,
      message: '登出成功'
    }
  } catch (error) {
    console.error('登出失败:', error)
    ctx.status = 500
    ctx.body = { code: 500, message: '服务器内部错误' }
  }
})

module.exports = router 